package com.dk.auth.core.service;

import com.dk.common.exception.BusinessException;
import com.dk.auth.core.dbbase.QUserPO;
import com.dk.auth.core.dbbase.UserPO;
import com.dk.auth.core.dbbase.UserRepository;
import com.dk.common.model.UserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Optional;

@Service
public class UserService {

    private static final QUserPO qUserPO = QUserPO.userPO;

    @Autowired
    private UserRepository userRepository;

    public Optional<UserDTO> findByName(String name) {
        List<UserPO> userPOList = (List<UserPO>) userRepository.findAll(qUserPO.userName.eq(name));
        if (CollectionUtils.isEmpty(userPOList)) {
            return Optional.empty();
        }
        if (userPOList.size() > 1) {
            throw new BusinessException("账户异常！");
        }
        UserPO userPO = userPOList.get(0);
        return Optional.of(UserDTO.builder()
                .id(userPO.getId())
                .userName(userPO.getUserName())
                .nickName(userPO.getNickName())
                .password(userPO.getPassword())
                .build());
    }
}
